package DDL;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import DuiXiang.TableModel;

/**
 * @author胡伟强
 *
 */
public class CreatTable {
	// 创建一张表
	@SuppressWarnings("finally")
	public static boolean creatTable(String dataBaseName, String tableName,
			List<TableModel> tabledetail) {

		File tablefile = new File("D:\\database\\" + dataBaseName + "\\"
				+ tableName + ".dbf");
		File tableDateFile=new File("D:\\database\\" + dataBaseName + "\\"
				+ tableName + ".dat");
		if (!tablefile.exists()) {
			try {
				tablefile.createNewFile();
				tableDateFile.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				System.out.println("目录不存在或此数据库不存在");
				e.printStackTrace();
				return false;
			}
		}
		else
		{
			System.out.println("此表已存在");
			return false;
		}
		Iterator<TableModel> iterator = tabledetail.iterator();
		FileWriter filewriter = null;
		BufferedWriter bufferwriter = null;
		try {
			filewriter = new FileWriter(tablefile);
			bufferwriter = new BufferedWriter(filewriter);
			TableModel temptablemodel = new TableModel();
			while (iterator.hasNext()) {
				temptablemodel = iterator.next();
				
				bufferwriter.write(temptablemodel.getsFieldName() + ",");// 字段名
				bufferwriter.write(temptablemodel.getsType() + ",");// 字段类型
				bufferwriter.write(temptablemodel.getiSize() + ",");// 字长
				bufferwriter.write(temptablemodel.getbKey() + ",");// 是否为主键
				bufferwriter.write(temptablemodel.getbNullFlag() + ",");//是否可以为null
				bufferwriter.write(temptablemodel.getbValidFlag());//是否有效
				bufferwriter.newLine();
			}
			bufferwriter.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("写数据时出错");
			return false;
		} finally {
			try {
				bufferwriter.close();
				filewriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return true;
		}
	}
}
